import Mock from "mockjs";

Mock.setup({
    timeout: 1000
})

let List = []
const count = 600
for (let i = 0; i < count; i++) {
    List.push(Mock.mock({
        id: i,
        name: Mock.Random.cname(),
        gender: Mock.Random.cword("01", 1, 1),
        email: Mock.Random.email(),
        phone: /^1[3-9][0-9]{9}$/,
        date: Mock.Random.datetime(),
    }))
}
Mock.mock(/\/user\/mock/, "get", {
    data: List
})
Mock.mock(/\/user\/adduser/, "post", config => {
    let obj = JSON.parse(config.body)
    obj.data.id = List.length
    if (obj.data.gender == "男") {
        obj.data.gender = 0
    } else if (obj.data.gender == "女") {
        obj.data.gender = 1
    }
    List.unshift(obj.data)
    return List
})
Mock.mock(/\/user\/updateuser/, "put", config => {
    let obj = JSON.parse(config.body)
    List.some((item, index) => {
        if (item.id == obj.data.id) {
            List.splice(index, 1, obj.data)
        }
    })
    return List
})
Mock.mock(/\/user\/deluser/, "delete", (config) => {
    let obj = getData(config.url)
    List.some((item, index) => {
        if (item.id == obj.id) {
            List.splice(index, 1)
        }
    })
    return List
})

function getData(str) {
    const search = str.split("?")[1]
    if (!search) {
        return {}
    }
    return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}




let shopList = [];
const num = 200;
for (let i = 0; i < num; i++) {
    shopList.push(Mock.mock({
        id: i,
        shopname: Mock.Random.cword(3),
        shopdesc: Mock.Random.cword(7),
        date: Mock.Random.datetime(),
    }))
}

Mock.mock(/\/shop\/mock/, "get", config => {
    config
    return shopList
})
Mock.mock(/\/shop\/updateshop/, "put", config => {
    let obj = JSON.parse(config.body)
    shopList.some((item, index) => {
        if (item.id == obj.data.id) {
            shopList.splice(index, 1, obj.data)
        }
    })
    return shopList
})

Mock.mock(/\/shop\/delshop/, "delete", (config) => {
    let obj = getData(config.url)
    shopList.some((item, index) => {
        if (item.id == obj.id) {
            shopList.splice(index, 1)
        }
    })
    return shopList
})

Mock.mock(/\/shop\/addshop/, "post", config => {
    let obj = JSON.parse(config.body)
    obj.data.id = shopList.length
    shopList.unshift(obj.data)
    return shopList
})